package cn.edu.xzit.config;

import cn.edu.xzit.pojo.User;
import cn.edu.xzit.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService service;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了====================>用户授权");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=====================>登录认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = service.findUserByName(token.getUsername());
        if (user == null) {//没有该用户
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        //将登陆用户放入到session中
        subject.getSession().setAttribute("loginUser", user);
        //密码认证
        return new SimpleAuthenticationInfo(user, user.getPwd(), "");
    }
}
